<!--  -->
<template>
  <div class="main">
    <CustomForm
      :formInline="formInline"
      @onSubmit="onSubmit"
      @resetTable="resetTable"
      :showAction="true"
    >
      <el-form-item label="货主公司">
        <!-- <el-select v-model="companyForm" filterable placeholder="请选择货主公司" @change="selectChange">
                <el-option v-for="(item,index) in companyList" :key="index" :label="item.company_name" :value="index">
                </el-option>
        </el-select>-->
        <el-input placeholder="请输入货主公司名" type="text" v-model="formInline.company"></el-input>
      </el-form-item>
      <template slot="btnBoxHeader">
        <el-button type="success" @click.prevent="addDomain">添加新地址</el-button>
      </template>
    </CustomForm>

    <!-- <div class="add-button">
      <el-button type="primary" @click.prevent="addDomain()">添加新地址</el-button>
    </div>-->

    <div class="scroll">
      <el-table :data="addressList" height="610" tooltip-effect="dark" style="width: 100%;">
        <el-table-column prop="id" label="ID"  align="center"></el-table-column>

        <el-table-column prop="name" label="联系人" align="center"></el-table-column>
        <el-table-column prop="phone" label="联系人电话" align="center"></el-table-column>
        <el-table-column prop="company_name" label="货主公司"  align="center" :show-overflow-tooltip="true"></el-table-column>

        <el-table-column label="地址" align="center" width="250" :show-overflow-tooltip="true">
          <template slot-scope="props">
            <span>{{ props.row.province + "-" + props.row.city + '-' + props.row.area }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="detail" label="详细地址" width="300" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDeleteDialog(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="formInline.page"
        :page-sizes="$pageSizeList"
        :page-size="formInline.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-dialog title="添加地址" :visible.sync="dialogVisible" width="50%" :before-close="handleClose" :close-on-click-modal="false">
      <AddressDialog v-if="dialogVisible" :companyList="companyList" @addSuccess="dialogVisible = false,getAdressList()" />
      <!-- <el-form
        ref="addressFormRef"
        :model="addressform"
        label-width="200px"
        :rules="addressRules"
        class="address-form"
      >
        <el-form-item label="货主公司" prop="owner_id">
          <el-select filterable v-model="addressform.owner_id" placeholder="请选择货主公司">
            <el-option
              v-for="(item, index) in companyList"
              :key="index"
              :label="item.company_name"
              :value="item.owner_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在地区" prop="areaArr">
          <el-cascader v-model="addressform.areaArr" placeholder="请选择所在地区" :options="regionData" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input v-model="addressform.detail" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="name">
          <el-input v-model="addressform.name" placeholder="请输入联系人"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="addressform.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label>
          <el-button type="primary" @click="onSubmitAddress('addressFormRef')">添加新地址</el-button>
        </el-form-item>
      </el-form> -->
    </el-dialog>

    <el-dialog title="编辑地址" :visible.sync="dialogVisibleEdit" width="50%" :before-close="handleClose">
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="200px"
        :rules="addressRules"
        class="address-form"
      >
        <el-form-item label="货主公司" prop="owner_id">
          <el-select filterable v-model="editForm.owner_id" placeholder="请选择货主公司">
            <el-option
              v-for="(item, index) in companyList"
              :key="index"
              :label="item.company_name"
              :value="item.owner_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在地区" prop="areaArr">
          <el-cascader v-model="editForm.areaArr" placeholder="请选择所在地区" :options="regionData" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input v-model="editForm.detail" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入联系人"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label>
          <el-button type="primary" @click="onSubmitEdit('editFormRef')">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      title="确认删除"
      :visible.sync="removeConfirmDialog"
      width="30%"
      :before-close="handleCloseRomove"
    >
      <span style="font-size: 18px;">确认删除ID为:{{ removeId }}的地址吗?</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="removeConfirmDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllCompany,
  getCompanyAddress,
  delCompanyAddress,
  addAddress,
  editCompanyAddress
} from "@/api/businessUser/release";
import { regionData } from "element-china-area-data";
import { getCodeToText } from "@/utils/tool.js";
import AddressDialog from "../releaseWaybill/components/AddressDialog.vue";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    AddressDialog
  },
  data() {
    var validatePhone = (rule, value, callback) => {
      if (
        !/^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\d{8}$/.test(
          value
        )
      ) {
        callback(new Error("请输入正确的手机号格式"));
      } else {
        callback();
      }
    };
    //这里存放数据
    return {
      regionData,
      addressList: [],
      dialogVisible: false,
      dialogVisibleEdit:false,
      removeConfirmDialog: false,
      removeId: "",
      removeRow: {},
      // companyForm:'',
      formInline: {
        page: 1,
        pageSize: 10,
        company: ""
      },
      companyList: [],
      total: 0,
      addressform: {
        owner_id: "",
        areaArr: "", //选择的省市区数组
        phone: "",
        name: "",
        detail: "",
        city_code: "",
        province: "", //省
        city: "", //城市
        area: "" //区
      },
      editForm:{
        id:"",
        owner_id: "",
        province:"",
        city:"",
        area:"",
        detail:"",
        name:"",
        phone:"",
        lat:"",
        lng:"",
        // city_code: "",
      },

      addressRules: {
        owner_id: [
          { required: true, message: "请选择货主公司", trigger: "change" }
        ],
        areaArr: [
          { required: true, message: "请选择选择收货地区", trigger: "change" }
        ],
        detail: [
          { required: true, message: "请填写详细地址", trigger: "change" }
        ],
        name: [{ required: true, message: "请填写联系人", trigger: "change" }],
        phone: [
          {
            required: true,
            validator: validatePhone,
            trigger: ["blur", "change"]
          }
        ]
      }
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    async getCompanyList() {
      let result = await getAllCompany();
      if (result.code == 200) {
        this.companyList = result.data;
      }
    },
    selectChange(val) {
      let obj = this.companyList[val];
      console.log("obj", obj);
      this.formInline.company = obj.company_name;
      this.formInline.owner_id = obj.owner_id;
    },
    onSubmit() {
      this.formInline.page = 1;
      this.getAdressList();
    },
    resetTable() {
      // this.companyForm = '';
      this.formInline = {
        page: 1,
        pageSize: 10,
        company: ""
      };
      this.getAdressList();
    },
    addDomain() {
      this.dialogVisible = true;
    },
    //获取地址列表
    async getAdressList() {
      let res = await getCompanyAddress(this.formInline);
      if (res.code == 200) {
        this.addressList = res.data.data;
        this.total = res.data.total;
      } else {
        this.$message({
          type: "error",
          message: res.info
        });
      }
    },

    //删除的dialog框
    handleDeleteDialog(index, row) {
      this.removeConfirmDialog = true;
      this.removeId = row.id;
      this.removeRow = row;
    },
    //编辑
    handleEdit(index,row){
      console.log('row',row);
      let owner_id = row.user_id;
      let city_code = row.city_code;
      let areaArr = [city_code.slice(0,2),city_code.slice(0,4),city_code]; //选择的省市区数组
      this.editForm = {
        ...row,
        owner_id,
        areaArr
      };
      this.dialogVisibleEdit = true;
    },
    async onSubmitEdit(formName){
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (this.editForm.areaArr) {
            this.editForm.city_code = this.editForm.areaArr[2];
          }
          
          let codeArr = getCodeToText(this.editForm.areaArr);
          this.editForm.province = codeArr[0];
          this.editForm.city = codeArr[1];
          this.editForm.area = codeArr[2];
          let res = await editCompanyAddress({
            province: this.editForm.province,
            city: this.editForm.city,
            area: this.editForm.area,
            name: this.editForm.name,
            phone: this.editForm.phone,
            detail: this.editForm.detail,
            city_code: this.editForm.city_code,
            lat:this.editForm.lat,
            lng:this.editForm.lng,
            owner_id:this.editForm.owner_id,
            id:this.editForm.id,
          });
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "编辑地址成功!"
            });
            this.getAdressList();
            this.dialogVisibleEdit = false;
          } else {
            this.$message({
              type: "error",
              message: res.info
            });
          }
        } else {
          console.log(this.addressform);
          return false;
        }
      });
    },
    //删除地址
    async handleDelete() {
      let res = await delCompanyAddress({
        id: this.removeId,
        owner_id: this.removeRow.user_id
      });
      if (res.code == 200) {
        this.$message({
          type: "success",
          message: true ? "删除地址成功!" : "编辑地址成功!"
        });
        this.getAdressList();
      } else {
        this.$message({
          type: "error",
          message: res.info
        });
      }
      this.removeConfirmDialog = false;
    },
    handleClose() {
      this.dialogVisible = false;
      this.dialogVisibleEdit = false;
    },
    handleCloseRomove() {
      this.removeConfirmDialog = false;
    },
    //添加新地址
    async onSubmitAddress(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          console.log(this.addressform);
          if (this.addressform.areaArr) {
            this.addressform.city_code = this.addressform.areaArr[2];
          }
          
          let codeArr = getCodeToText(this.addressform.areaArr);
          this.addressform.province = codeArr[0];
          this.addressform.city = codeArr[1];
          this.addressform.area = codeArr[2];
          let res = await addAddress({
            province: this.addressform.province,
            city: this.addressform.city,
            area: this.addressform.area,
            name: this.addressform.name,
            phone: this.addressform.phone,
            detail: this.addressform.detail,
            city_code: this.addressform.city_code
          });
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: true ? "添加地址成功!" : "编辑地址成功!"
            });
            this.getAdressList();
            this.dialogVisible = false;
          } else {
            this.$message({
              type: "error",
              message: res.info
            });
          }
        } else {
          console.log(this.addressform);
          return false;
        }
      });
    },
    handleCurrentChange(page) {
      //改变page回调
      this.formInline.page = page;
      this.getAdressList();
    },
    handleSizeChange(pageSize) {
      //改变pageSize
      this.formInline.pageSize = pageSize;
      this.formInline.page = 1;
      this.getAdressList();
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getCompanyList();
    this.getAdressList();
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: calc(100vh - 100px);
  background-color: #fff;
  border-radius: 10px;
  padding: 10px;
  overflow: auto;

  .scroll {
    width: 100%;
    flex: 1;
  }

  .add-button {
    padding: 20px;
    padding-top: 0;
  }
}
</style>